<?php

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\BaseHelper;
use app\common\Common;
use app\admin\model\Memberlevel;
use app\admin\model\Store;
use app\admin\model\Product;
use app\admin\model\Productcategory;

use think\Db;
use think\Request;

class Flashsale extends Base
{

    public function _initialize()
    {
        parent::_initialize();

        $defaultWhere = $this->getDefaultWhere();
        $defaultWhere['status'] = ['neq', 0];
        $this->defaultWhere = $defaultWhere;
        $this->defaultOrder = 'create_date DESC';

        if($this->request->action() == 'add' || $this->request->action() == 'edit'){
            // 会员等级
            $memberlevelList = Memberlevel::where(['status' => 1])->field('id, name')->select();
            // 门店
            $storeList = Store::where(['business_end_time' => ['gt', date('Y-m-d H:i:s')]])->field('id, name')->select();

            $this->assign('memberlevelList', $memberlevelList);
            $this->assign('storeList', $storeList);
        }
    }

    public function index(){

        return parent::index();
    }

    /**
     * Add
     */
    public function add(Request $request){

        return parent::add($request);
    }

    /**
     * Edit
     */
    public function edit(Request $request){
        $model = model($this->model);
        $id = $request->param('id');
        // Get data info
        $info = $model->find($id);
        if(!$info){
            return $this->error('error !', 'admin/' . strtolower($this->model) . '/index');
        }

        $info['start_time'] = substr($info['start_time'],0,10);
        $info['end_time'] = substr($info['end_time'],0,10);
        $info['product'] = Product::where('id', $info['product_id'])->field('name, price')->find();
        $info['store_ids'] = explode(',', $info['store_ids']);
        $info['to_users'] = explode(',', $info['to_users']);

        return $this->fetch($this->editView, [
            'info' => $info
        ]);
    }

    /**
     * Save Post
     */
    public function savePost(Request $request){
        $model = model($this->model);

        if ($request->isPost()) {
            Db::startTrans();
            try {
                $data = $request->param();

                $data['ori_price'] = $data['ori_price'] * 100;
                if ($data['promotion_type'] == 1) {
                    // 特价
                    $data['promotion_discount'] = $data['price'] * 100;
                    // 折后价
                    $data['markup'] = $data['promotion_discount'];
                } elseif ($data['promotion_type'] == 2) {
                    // 折扣
                    $data['promotion_discount'] = $data['discount'] * 100;
                    // 折后价
                    $data['markup'] = ceil($data['ori_price'] * $data['promotion_discount'] / 1000); // 向上取整
                } else {
                    // 立减
                    $data['promotion_discount'] = $data['reduce_price'] * 100;
                    // 折后价
                    $data['markup'] = $data['ori_price'] - $data['promotion_discount'];
                }
                $data['end_time'] = $data['end_time'] . ' 23:59:59';

                // 该商品是否已参加过其他活动
                $usedInfo = $this->isUsed($data['product_id']);
                if($usedInfo['code'] != 1){
                    return $this->error($usedInfo['msg']);
                }

                if ($data['id']) {
                    // Update data
                    $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
                    $logInfo = $this->admin->name . '更新了一条' . $this->model . '数据。';
                    $afterAction = '_after_update';
                } else {
                    // Insert data
                    $data['id'] = BaseHelper::getUUID();
                    $result = $model->save($data);
                    $logInfo = $this->admin->name . '添加了一条' . $this->model . '数据。';
                    $afterAction = '_after_insert';
                }

                if($result !== false) {
                    // 更新商品类型
                    $productRes = Product::where(['id' => $data['product_id']])->update(['type' => 1]);
                    if ($productRes === false) {
                        Db::rollback();
                        return $this->error('更新商品类型失败');
                    }

                    // 删除相同的折扣商品
                    $res = $model->where(['product_id' => $data['product_id'], 'id' => ['neq', $data['id']]])->delete();
                    if ($res === false) {
                        Db::rollback();
                        return $this->error('失败');
                    }

                    // Query执行后的操作
                    $model->$afterAction($data);

                    // 写入日志
                    Common::adminLog($request, $logInfo);

                    Db::commit();
                    return $this->success('保存成功！', 'admin/' . strtolower($this->model) . '/index');
                } else {
                    Db::rollback();
                    return $this->error($model->getError());
                }
            } catch (Exception $e) {
                Db::rollback();
                return $this->error($e->getMessage());
            }

        } else {
            return $this->error('提交方式错误！');
        }
    }

    /**
     * Delete
     */
    public function delete(){
        $request = $this->request;
        $id = $request->param('id');

        $model = model($this->model);
        $info = $model->find(['id', $id]);
        if(!$info){
            return redirect('admin/'.$this->model.'/index');
        }

        Db::startTrans();
        try {
            $result = $model->where('id', $id)->update(['status' => 0]);
            if ($result !== false) {
                // 更新商品类型
                $productRes = Product::where(['id' => $info['product_id']])->update(['type' => 0]);
                if ($productRes === false) {
                    Db::rollback();
                    return $this->error('更新商品类型失败');
                }

                // Query执行后的操作
                $model->_after_delete($id);

                $logInfo = $this->admin->name . '删除了1条' . lang($this->model) . '数据。';
                Common::adminLog($request, $logInfo);

                Db::commit();
                return $this->success('删除成功！', 'admin/' . strtolower($this->model) . '/index');
            } else {
                Db::rollback();
                return $this->error('删除失败！', 'admin/' . strtolower($this->model) . '/index');
            }
        } catch (Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    /**
     * 处理列表数据
     */
    public function handleListData($data){
        foreach ($data as $item) {
            $productInfo = Product::where('id', $item['product_id'])->field('name, purchase_price')->find();
            $item['product_name'] = $productInfo['name'];
            $item['purchase_price'] = $productInfo['purchase_price'];

            // 活动价
            switch ($item['promotion_type']) {
                case 1:
                    $item['promotion_discount'] = $item['promotion_discount'] / 100;
                    break;
                case 2:
                    $item['promotion_discount'] = $item['promotion_discount'] / 100 . ' 折';
                    break;
                case 3:
                    $item['promotion_discount'] = '立减 ' . $item['promotion_discount'] / 100;
                    break;
                default : break;
            }
            // 每单限购
            switch ($item['buy_limit_type']) {
                case 1:
                    $item['buy_limit'] = 1;
                    break;
                case 2:
                    $item['buy_limit'] = '不限';
                    break;
                case 3:
                    $item['buy_limit'] = $item['buy_limit_num'];
                    break;
                default : break;
            }
            // 面向用户
            switch ($item['to_user_type']) {
                case 1:
                    $item['to_users'] = '全部用户';
                    break;
                case 2:
                    $item['to_users'] = '新用户';
                    break;
                case 3:
                    $memberLevelNames = Memberlevel::whereIn('id', $item['to_users'])->column('name');
                    $item['to_users'] = implode(',', $memberLevelNames);
                    break;
                default : break;
            }
            // 适用范围
            switch ($item['range']) {
                case 1:
                    $item['range'] = '全部门店';
                    break;
                case 2:
                    $item['range'] = '线上门店';
                    break;
                case 3:
                    $storeNames = Store::whereIn('id', $item['store_ids'])->column('name');
                    $item['range'] = implode(',', $storeNames);
                    break;
                default : break;
            }
            // 状态
            if (substr($item['start_time'], 0, 10) > date('Y-m-d')) {
                $item['act_status'] = '待生效';
            } else {
                if (substr($item['end_time'], 0, 10) >= date('Y-m-d')) {
                    $item['act_status'] = '已生效';
                } else {
                    $item['act_status'] = '已过期';
                }
            }
        }

        return $data;
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if(isset($param['name']) && $param['name']){
            $productIds = Product::where(['name' => ['like', '%'.$param['name'].'%']])->column('id');
            $where['product_id'] = ['in', $productIds];
        }
        // 状态
        if(isset($param['act_status']) && $param['act_status']){
            switch ($param['act_status']) {
                case 1:
                    // 待生效
                    $where['start_time'] = ['gt', date('Y-m-d H:i:s')];
                    break;
                case 2:
                    // 已生效
                    $where['start_time'] = ['elt', date('Y-m-d H:i:s')];
                    $where['end_time'] = ['egt', date('Y-m-d H:i:s')];
                    break;
                case 3:
                    // 已过期
                    $where['start_time'] = ['elt', date('Y-m-d H:i:s')];
                    $where['end_time'] = ['lt', date('Y-m-d H:i:s')];
                    break;
                default : break;
            }
        }
        // 时间
        if(isset($param['range_date']) && $param['range_date']){
            $rangeDate = explode(' ~ ', $param['range_date']);
            $startTime = $rangeDate[0];
            $endTime = $rangeDate[1];

            $where['start_time'] = ['egt', $startTime];
            $where['end_time'] = ['elt', $endTime];
        }

        return $where;
    }

    /**
     * 检查折扣特价商品是否已存在
     */
    public function checkProduct(){
        $productId = $this->request->param('product_id');
        $model = model($this->model);
        $buyProduct = $model->where(['product_id' => $productId, 'status' => 1])->field('product_id')->find();

        if($buyProduct){
            return json(['status' => 1]);
        }else{
            return json(['status' => 0]);
        }
    }

    /**
     * 是否被使用过
     */
    protected function isUsed($productId){
        if(!$productId){
            return ['code' => 0, 'msg' => '参数错误'];
        }
        // 该商品是否在买赠活动中
        $buygiftsWhere = [
            'buy_product_id' => $productId,
            'status' => ['neq', 0]
        ];
        $buygifts = \app\admin\model\Buygifts::where($buygiftsWhere)->find();
        if($buygifts){
            return ['code' => 0, 'msg' => '该商品已在买赠活动中，不能再参与此活动'];
        }

        // 该商品是否在加价换购活动中
        $repurchaseWhere = [
            'product_id' => $productId,
            'status' => ['neq', 0]
        ];
        $repurchase = \app\admin\model\Repurchase::where($repurchaseWhere)->find();
        if($repurchase){
            return ['code' => 0, 'msg' => '该商品已在加价换购活动中，不能再参与此活动'];
        }

        return ['code' => 1, 'msg' => ''];
    }

    /**
     * 检查购买商品是否被使用过
     */
    public function checkUsed(){
        $productId = $this->request->param('product_id');
        $usedInfo = $this->isUsed($productId);

        return json($usedInfo);
    }

    /**
     * 选择商品
     */
    public function selectProducts(){
        $request = $this->request;
        $param = $request->param();

        if($request->isAjax()){
            $model = new Product();

            // 每页起始条数
            $start = ($param['page'] - 1) * $param['limit'];
            // 每页显示条数
            $length = $param['limit'];
            $where = [
                'status' => 1
            ];
            if(isset($param['name']) && $param['name']){
                $where['name'] = ['like', '%'.$param['name'].'%'];
            }
            $fields = 'id, img_url, name, bar_code, category_id, purchase_price, price, wholesale_price, member_integral';
            $order = 'create_date DESC';
            $data = $model->where($where)->field($fields)->order($order)->limit($start, $length)->select();
            if($data){
                foreach ($data as $item) {
                    // 分类
                    $item['category_id'] = Productcategory::where('id', $item['category_id'])->value('name');
                    // 库存
                    $item['qty'] = $model->getStock($item['id']);
                }
            }
            $count = $model->where($where)->count();

            $result = [
                'code' => '0',
                'msg' => '',
                'data' => $data,
                'count' => $count,
            ];

            return json($result);
        }

        return $this->view->fetch('flashsale/select_products', [
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param()
        ]);
    }

    /**
     * 设置有效日期
     */
    public function setEffectiveDate(){
        $request = $this->request;
        $param = $request->param();

        return $this->view->fetch('flashsale/set_effective_date', [
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param()
        ]);
    }
}